package com.rtsapp.server.gamelog.analyze.stat;

import com.rtsapp.server.gamelog.analyze.controller.LoginController;
import com.rtsapp.server.gamelog.analyze.dao.CommonDao;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liwang on 16-8-30.
 */
public class ChannelUtils {

    public static List<String> getChannelsByUserName( final CommonDao dao, final HttpServletRequest request ) {
        String[] channelsArry = getChannelsFromDB( dao, request );
        if ( channelsArry == null || channelsArry.length == 0 ) {
            return null;
        }

        List<String> channelList = new ArrayList<>( );
        for ( String channelName : channelsArry ) {
            channelList.add( channelName );
        }

        return channelList.isEmpty( ) ? null : channelList;
    }

    public static String[] getChannels( final CommonDao dao, final HttpServletRequest request, final String paramName ) {
        String[] allowChannels = getChannelsFromDB( dao, request );
        final boolean allChannels = isArrayEmpty( allowChannels );

        String[] reqChannels = request.getParameterValues( paramName );
        if ( isArrayEmpty( reqChannels ) ) {
            return allowChannels;
        }

        List<String> channelList = new ArrayList<>( );
        for ( String reqChannel : reqChannels ) {
            if ( allChannels || isArrayContainsParam( allowChannels, reqChannel ) ) {
                channelList.add( reqChannel );
            }
        }

        return channelList.toArray( new String[ channelList.size( ) ] );
    }


    private static String[] getChannelsFromDB( final CommonDao dao, final HttpServletRequest request ) {
        Object userNameObj = request.getSession( ).getAttribute( LoginController.SESSION_ATTR );
        String userName;
        if ( userNameObj == null || ( userName = userNameObj.toString( ) ).isEmpty( ) ) {
            return null;
        }

        String channelsStr = dao.selectChannelNamesStrByUserName( userName );
        if ( channelsStr == null || ( channelsStr = channelsStr.trim( ) ).isEmpty( ) ) {
            return null;
        }

        String[] channelsArry = channelsStr.split( "#" );
        return channelsArry.length > 0 ? channelsArry : null;
    }

    private static <V> boolean isArrayEmpty( V[] vs ) {
        return vs == null || vs.length < 1;
    }

    private static <V> boolean isArrayContainsParam( V[] vs, V param ) {
        if ( param == null || isArrayEmpty( vs ) ) {
            return false;
        }

        for ( int i=0;i<vs.length;i++ ) {
            if ( param.equals( param ) ) {
                return true;
            }
        }

        return false;
    }

    public static <V> boolean isChannelsValid( V[] vs ) {
        return vs == null || vs.length > 0;
    }

}
